<template>
    <div id="rightdown" style="width: 600px; height: 400px;"></div>
</template>

<script setup>
import {  defineProps, watch, nextTick,ref } from 'vue';
import * as echarts from 'echarts';
  import 'echarts-wordcloud'; 
  // 定义 props，接收父组件传递的数据
  const props = defineProps({
    childData5: Array
  });
  
  const words = ref([])
 
  let myChart = null; // 存储 ECharts 实例
  function extractAndTransformKeywords(dataArray) {
    const targetObject = dataArray.find(item => item.key_word !== null);
    if (!targetObject || !targetObject.key_word) {
        console.warn("缺少有效的key_word数据");
        return [];
    }
    const keyWordData =targetObject.key_word;
    const transformedData = [];
    
    for (const [name, value] of Object.entries(keyWordData)) {
        transformedData.push({ name, value });
    }
    return transformedData;
}
// 在你的watcher回调中使用此函数
watch(() => props.childData5, async (newVal) => {
    await nextTick(); // 等待DOM更新
    words.value = newVal; 
    // 假设words.value现在是一个对象数组，提取并转换key_word
    const transformedWords = extractAndTransformKeywords(words.value);
    const echartsContainer = document.getElementById("rightdown");
    
    if (myChart) {
      // 如果已经存在 ECharts 实例，则先销毁它
      myChart.dispose();
    }
    // 初始化 ECharts 实例
    myChart = echarts.init(echartsContainer);
    // 检查childData1是否已定义
    if (!props.childData5 || props.childData5.length === 0) {
      console.warn('childData1 is not ready yet.');
      return; // 如果数据未准备好，直接返回不执行后续逻辑
    }
    const option = {
    backgroundColor: '',
    tooltip: {
        show: true
    },
    toolbox: {
        feature: {
            saveAsImage: {
                iconStyle: {
                    normal: {
                        color: '#FFFFFF'
                    }
                }
            }
        }
    },
    series: [{
        name: '关键词',
        type: 'wordCloud',
        //size: ['9%', '99%'],
        sizeRange: [6, 66],
         rotationRange: [0, 90],
        rotationStep: 90,
        //textRotation: [0, 45, 90, -45],
        textPadding: 0,
        textStyle: {
            normal: {
                color: function() {
                    return 'rgb(' + [
                        Math.round(Math.random() * 160),
                        Math.round(Math.random() * 160),
                        Math.round(Math.random() * 160)
                    ].join(',') + ')';
                }
            },
            emphasis: {
                shadowBlur: 10,
                shadowColor: '#333'
            }
        },
        data:transformedWords
    }]
};
    myChart.setOption(option);
    // 其他逻辑，如初始化ECharts等...
}, { immediate: true });
  
</script>